package com.heima.media.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.MediaEnum;
import com.heima.common.minio.service.MinIOService;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-29
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {


    @Autowired
    private MinIOService minIOService;

    /**
     *保存自媒体用户素材
     * @param file  素材文件
     * @return
     */
    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile file) {
        //1.上传图片到minio中 获的上传后的文件地址
        String filterUrl = minIOService.upload(file);
        //2.保存自媒体用户的素材表
        WmMaterial wmMaterial = new WmMaterial();
        //2.1 从线程中获取当前用户的信息
        wmMaterial.setUserId(UserThreadLocalUtil.get().getUserId());
        wmMaterial.setType(MediaEnum.MEDIA_MATERIAL_TYPE_IMG.getVal());
        wmMaterial.setUrl(filterUrl);
        wmMaterial.setIsCollection(false);
        this.save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 分页查询当前用户的素材表
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult listByPage(WmMaterialDto wmMaterialDto) {

        User user = UserThreadLocalUtil.get();
        //1.构建分页对象
        Page<WmMaterial> materialPage = new Page<>(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        //2.构建查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmMaterial::getUserId,user.getUserId());
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //判断收藏状态
        if (wmMaterialDto.getIsCollection()!=null){
            queryWrapper.eq(WmMaterial::getIsCollection,wmMaterialDto.getIsCollection());
        }
        //3.执行查询
        this.page(materialPage,queryWrapper);
        //4.封装返回结果
        return new PageResponseResult(wmMaterialDto.getPage(),wmMaterialDto.getSize(),materialPage.getTotal(),materialPage.getRecords());
    }
}
